﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Employees_EmplyeeList : System.Web.UI.Page
{
    private Srvtools.WebDataSet WMaster;
    MasterPage_MasterPage master = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            Session["HrBack"] = null;

            master = (MasterPage_MasterPage)this.Page.Master;

            BindAction(true);

            if (!IsPostBack)
            {

                InitializeComponent(false);

                if (Request["ItemParam"].ToString() == "")
                {
                    object DeptId = Srvtools.CliUtils.CallMethod("SDepartment", "GetDptIdByEmpId", new object[] { Convert.ToInt32(Srvtools.CliUtils.GetValue("_UserCode")[1]) })[1];
                    DataTable dt = ((DataSet)DeptId).Tables[0];

                    Depart.AllDpt = dt;
                    //WMaster.SetWhere("DepartmentId like '" + Depart.ParentDpt + "%'");

                }

                if (Request["IsSearch"] != null)
                {
                    IsSearch();
                }
                else
                {


                    //WMaster.Active = false;
                    WMaster.Active = false;

                    Masters.DataSource = WMaster;

                    wgvMaster.Visible = false;

                    ddlStatus.SelectedValue = "1";
                }

                master.PicUrl = "~/image/PageIcon/emp.jpg";

                master.IntiBar();

            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }



    private void InitializeComponent(bool active)
    {
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Employees_EmplyeeList));
        this.WMaster = new Srvtools.WebDataSet();
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).BeginInit();
        // 
        // WMaster
        // 
        this.WMaster.Active = active;
        this.WMaster.AlwaysClose = false;
        this.WMaster.PacketRecords = -1;
        this.WMaster.Position = -1;
        this.WMaster.RemoteName = "SEmployees.ViewEmpList";
        this.WMaster.ServerModify = false;
        ((System.ComponentModel.ISupportInitialize)(this.WMaster)).EndInit();
    }


    private string BindAction(bool Inti)
    {

        if (Request["ItemParam"] != null)
        {
            try
            {
                if (Request["ItemParam"].ToString() != "")
                {
                    string[] iparam = Server.UrlDecode(Request["ItemParam"]).Split('?');

                    string action = iparam[0];

                    if (Inti)
                    {


                        master.PageName = "员工列表（人事）";



                        //liEmpLeave.Visible = HT[action[0]] != null ? true : false;
                        liAdd.Visible = action != null ? true : false;

                        return null;
                    }
                    else
                    {
                        return GetQuery(iparam[1].ToString());
                    }
                }
                else
                {

                    if (Inti)
                    {

                        master.PageName = "员工列表（主管）";



                        liAdd.Visible = false;
                        liGoToDpt.Visible = false;
                    }
                    else
                    {
                        return "&mode=&action=view&do=false";
                    }
                }
            }
            catch
            {
                return null;
            }
            //GetQuery(iparam[1]);

            //string[] query = iparam[1].Split(',');

            //return "&Mode=" + Server.UrlEncode(query[0] + "," + query[1] + "," + query[2] + "," + query[3]);
        }
        {
            return null;
        }
    }

    private string GetQuery(string Mode)
    {
        try
        {

            //string[] iparam = Server.UrlDecode(Request["ItemParam"]).Split('?');

            //string[] action = iparam[0].Split(',');



            return "&mode=" + Mode + "&action=edit&do=false";
        }
        catch
        {
            return null;
        }
    }

    protected void wgvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;

            //CheckBox chk = (CheckBox)e.Row.FindControl("chkStatus");
            //chk.Checked = drv["Empstatus"].ToString() == "1" ? true : false;

            //CheckBox EmpLeave = (CheckBox)e.Row.FindControl("EmpLeave");
            //EmpLeave.Enabled = drv["Empstatus"].ToString() == "1" ? true : false;

            Label lblStatus = (Label)e.Row.FindControl("lblStatus");
            lblStatus.Text = drv["Empstatus"].ToString() == "1" ? "<b>在职</b>" : "<font style='color:silver'>离职</font>";


            Literal litSex = (Literal)e.Row.FindControl("litSex");
            litSex.Text = drv["Sex"].ToString() == "True" ? "男" : "女";

            ImageButton imb = (ImageButton)e.Row.FindControl("imb");

            if (BindAction(false) != null)
            {
                if (drv["EmployeeId"].ToString() != "" && drv["EmployeeId"].ToString() != "0")
                {
                    imb.CommandArgument = "eid=" + drv["EmployeeId"].ToString() + BindAction(false);
                }
                else
                {
                    imb.CommandArgument = "";
                }
            }

            //ImageButton ibt = (ImageButton)e.Row.FindControl("ibdetail");
        }
    }


    private void IsSearch()
    {
        Search.CssClass = "OnHover";


        string strDep = Request["dpt"].ToString();
        if (strDep == "0")
        {
            strDep = "";
        }
        else
        {
            Depart.IsAfterBind = strDep;
            strDep = "And DepartmentId like ('" + strDep + "%')";
        }


        string sname = Request["emp"].ToString();
        if (sname != "")
        {
            SelUser.EmpName = Server.UrlDecode(sname);
            sname = "And EmpName like ('%" + Server.UrlDecode(sname) + "%')";
        }
        else
        {
            sname = "";
        }


        string Status = Request["status"].ToString();
        if (Status == "-1")
        {
            Status = "";
        }
        else
        {
            ddlStatus.SelectedValue = Status;
            Status = " And EmpStatus = " + Status;
        }

        InitializeComponent(true);

        WMaster.SetWhere("1=1 " + strDep + sname + Status);

        WMaster.Active = true;

        Masters.DataSource = WMaster;

        wgvMaster.Visible = true;

        Masters.Reload();
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        string url = "IsSearch=1";

        string strDep = Depart.SelectDepmanetId;
        if (strDep == "")
        {
            return;
        }
        else if (strDep == "0")
        {
            strDep = "";
            url += "&dpt=";
        }
        else
        {
            url += "&dpt=" + strDep;
            strDep = "And DepartmentId like ('" + strDep + "%')";

        }


        string sname = SelUser.EmpName;
        if (sname != "")
        {
            url += "&emp=" + Server.UrlEncode(sname);
            sname = "And EmpName like ('%" + sname + "%')";

        }
        else
        {
            url += "&emp=";
            sname = "";
        }

        string Status = ddlStatus.SelectedValue;
        if (Status == "-1")
        {
            url += "&status=-1";
            Status = "";
        }
        else
        {
            url += "&status=" + Status;
            Status = " And EmpStatus = " + Status;
        }

        Response.Redirect("EmployeesList.aspx?ItemParam=" + Request["ItemParam"].ToString() + "&" + url);
    }

    string GetWhere()
    {
        string Status = ddlStatus.SelectedValue;
        if (Status == "-1")
            Status = "";
        else
            Status = "EmpStatus = " + Status;

        string strDep = Depart.SelectDepmanetId;
        if (strDep == "")
            return string.Empty;
        else if (strDep == "0")
            strDep = "";
        else
            strDep = " And DepartmentId = '" + strDep + "'";

        string sname = SelUser.EmpName;
        if (sname != "")
            sname = " And EmpName like '%" + sname + "%'";
        else
            sname = "";


        return Status + strDep + sname;
    }

    string GetUrl()
    {
        return Request.Url.AbsoluteUri;
    }

    protected void Add_Click(object sender, EventArgs e)
    {
        Response.Redirect("EmployeeDetail.aspx?action=add");
    }

    protected void wgvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "show")
        {
            if (e.CommandArgument.ToString() != "")
            {
                Session["HrBack"] = Request.Url.ToString();

                Response.Redirect("EmployeeDetail.aspx?" + e.CommandArgument.ToString());
            }
        }
    }

    protected void EmpLeave_Click(object sender, EventArgs e)
    {
        Search.CssClass = "UnHover";

        ArrayList array = new ArrayList();
        //object[] objParm = new object[] { sqlarr };
        //object[] ret = CliUtils.CallMethod("Common", "SqlTran", objParm);

        for (int i = 0; i < wgvMaster.Rows.Count; i++)
        {
            if (((CheckBox)wgvMaster.Rows[i].FindControl("EmpLeave")).Checked)
            {
                //obj[i] = ((Label)wgvMaster.Rows[i].FindControl("lbl")).Text;

                array.Add(((Label)wgvMaster.Rows[i].FindControl("lbl")).Text);
            }
        }
        if (array.Count <= 0)
        {
            ClientScript.RegisterStartupScript(GetType(), "Msg", "alert('未选中离职人员，执行取消')", true);
            return;
        }

        object[] obj = new object[array.Count];

        for (int i = 0; i < array.Count; i++)
        {
            obj[i] = array[i];
        }

        object[] ret = Srvtools.CliUtils.CallMethod("SEmployees", "TranEmpLeave", obj);
        ClientScript.RegisterStartupScript(GetType(), "Msg", "alert('离职成功：" + ret[1].ToString() +
            "\\r\\r离职失败：" + ret[2].ToString() + "')", true);
        Search_Click(null, null);
    }

    protected void GoToDpt_Click(object sender, EventArgs e)
    {
        string[] iparam = Server.UrlDecode(Request["ItemParam"]).Split('?');
        Response.Redirect("EmployeeTreeView.aspx?ItemParam=edit?" + iparam[1]);
    }

    protected void DownLoad_Click(object sender, EventArgs e)
    {
        //Download();
        Response.Redirect("EmployeeExport_Choose.aspx?ItemParam=" + Request["ItemParam"].ToString() + "&module=" + Server.UrlEncode("人员信息") + "&where=" + Server.UrlEncode(GetWhere()) + "&referUrl=" + GetUrl());
    }

    private void Download()
    {
        object obj = Masters.InnerDataSet;

        string path = MapPath("~/UploadFile/Template/");

        DataTable dt = ((DataSet)obj).Tables[0];


        if (dt.Rows.Count <= 0)
        {
            ClientScript.RegisterStartupScript(GetType(), "Msg", "alert('没有记录')", true);
            return;
        }
        DataTable dts = GetDataTable();

        foreach (DataRow dr in dt.Rows)
        {
            DataRow SR = dts.NewRow();
            SR["员工编号"] = dr["EmployeeID"];
            SR["员工姓名"] = dr["EmpName"];
            SR["出生年月"] = dr["Birthday"];
            SR["身份证"] = dr["IDCard"];
            SR["在职状态"] = (dr["Empstatus"].ToString() == "1" ? "在职" : "离职");
            SR["性别"] = dr["Sex"].ToString() == "True" ? "男" : "女";

            SR["部门"] = (wdsDepartment.View.Table.Select("DepartmentId=" + dr["DepartmentId"].ToString()))[0]["DepartmentName"].ToString();
            SR["入职日期"] = dr["Accession"].ToString();
            SR["职位"] = (wdsJob.View.Table.Select("JobId=" + dr["JobId"].ToString()))[0]["JobName"].ToString();

            dts.Rows.Add(SR);
        }


        DataTable dtt = dts.Clone();
        dtt.Merge(dts);
        Srvtools.InfoDataSet ids = new Srvtools.InfoDataSet();
        ids.RemoteName = "GLModule.cmdColDEF";
        ids.RealDataSet.Tables.Add(dtt);

        ids.ToExcel(0, path + "emplist.xls");


        System.IO.FileInfo fn = new System.IO.FileInfo(path + "emplist.xls");

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        //HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fn.Name);
        HttpContext.Current.Response.AppendHeader("Content-Length", fn.Length.ToString());
        HttpContext.Current.Response.WriteFile(fn.FullName);
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();

    }

    private DataTable GetDataTable()
    {
        DataTable WTable = new DataTable("DownLoadDT");
        {
            WTable.Columns.Add(new DataColumn("员工编号", typeof(Int32)));
            WTable.Columns.Add(new DataColumn("员工姓名", typeof(string)));
            WTable.Columns.Add(new DataColumn("出生年月", typeof(DateTime)));
            WTable.Columns.Add(new DataColumn("身份证", typeof(string)));
            WTable.Columns.Add(new DataColumn("性别", typeof(string)));
            WTable.Columns.Add(new DataColumn("部门", typeof(string)));
            WTable.Columns.Add(new DataColumn("职位", typeof(string)));
            WTable.Columns.Add(new DataColumn("入职日期", typeof(string)));
            WTable.Columns.Add(new DataColumn("在职状态", typeof(string)));
        }
        return WTable;
    }
}
